package com.bianguo.android.iocdemo.view.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.bianguo.android.iocdemo.bean.PieBean;

import java.util.ArrayList;

public class PieView extends View {

    private int mCenterX, mCenterY;
    private Paint mPaint;
    private float mRadius;
    private ArrayList<PieBean> pieBeans;
    private float mCurrentAngle;

    public PieView(Context context) {
        this(context, null);
    }

    public PieView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PieView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);
        pieBeans = new ArrayList<>();
        mCurrentAngle = 0;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mCenterX = w / 2;
        mCenterY = h / 2;
        mRadius = (float) (Math.min(w, h) / 2 * 0.8);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(mCenterX, mCenterY, mRadius, mPaint);
        RectF mRectF = new RectF(mRadius, mRadius, 2 * mRadius, 2 * mRadius);
        for (PieBean pieBean : pieBeans) {
            mPaint.setColor(pieBean.getColor());
            float angle = pieBean.getAngle();
            canvas.drawArc(mRectF, mCurrentAngle, angle, true, mPaint);
            mCurrentAngle = angle;
        }
    }
}
